<?php

namespace App\Http\Controllers\Admin;

use App\Http\Services\MsgService;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Http\Services\RoleService;

class RoleController extends Controller
{
    /**
     *角色列表
     * @author: lican<364548233@qq.com>
     */
    public function index(Request $request){
        $this->validate($request, [
            'admin' => 'required',
        ]);
        $keyword = trim($request->input('keyword')) ?? '';
        $page = (int)$request->input('page') ?? 1;
        $pageSize = (int)$request->input('pageSize') ?? 10;
        $res = RoleService::roleList($keyword, $page, $pageSize);
        return $res;
    }

    /**
     *角色添加
     * @author lican<364548233@qq.com>
     */
    public function add(Request $request){
        $this->validate($request, [
            'admin' => 'required',
            'name' => 'required|between:2,8'
        ]);
        $admin = $request->input('admin');
        $name = trim($request->input('name'));
        $id = (int)$request->input('id');
        $res = RoleService::save($admin, $name, null, null, $id);
        return $res;
    }


    /**
     *角色删除
     * @author lican<364548233@qq.com>
     */
    public function delete(Request $request){
        $this->validate($request, [
            'admin' => 'required',
            'id' => 'required'
        ]);
        $id = trim($request->input('id'));
        $res = RoleService::delete($id);
        return $res;
    }

    /**
     *角色状态切换
     * @author: lican<364548233@qq.com>
     */
    public function trigger(Request $request){
        $this->validate($request, [
            'admin' => 'required',
            'id' => 'required|int'
        ]);
        $id = (int)$request->input('id');
        $res = RoleService::trigger($id);
        return $res;
    }

    /**
     *获取角色权限
     * @author: lican<364548233@qq.com>
     */
    public function getRoleRule(Request $request){
        $this->validate($request, [
            'admin' => 'required',
            'role_id' => 'required|int'
        ]);
        $roleId = (int)$request->input('role_id');
        $res = RoleService::getRoleRule($roleId, true);
        return MsgService::getMsg(0, ['list' => $res]);
    }

    /**
     *角色权限分配
     * @author: lican<364548233@qq.com>
     */
    public function division(Request $request){
        $this->validate($request, [
            'admin' => 'required',
            'admin_id' => 'required',
            'role_id' => 'required',
            'rules' => 'required'
        ]);

        $admin = $request->input('admin');
        $adminId = $request->input('admin_id');
        $roleId = (int)$request->input('role_id');
        $rules = $request->input('rules');
        $res = RoleService::division($admin, $adminId, $roleId, $rules);
        return $res;
    }

}
